package com.zpark.user;


import com.zpark.user.bean.User;
import com.zpark.user.utils.JDBCUtils;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * 注册流程：
 *      1、用户在注册页面输入数据
 *      2、用户点击注册按钮
 *      3、后台获取用户提交的数据
 *      4、校验数据
 *      5、实现用户输出功能（本质：将数据写入数据库）
 *          5.1、通过注册名字向数据库查询数据，如果有结果，说明该用户名已经吧注册过，此时注册失败，否则写入数据
 *      6、注册成功，重定向到登录页面
 */
@WebServlet("/user/reg.do")
public class RegServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 后台获取用户提交的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String sex = request.getParameter("sex");
        String[] languages = request.getParameterValues("language");
        String city = request.getParameter("city");

        // 校验数据（使用正则表达式校验）

        // 通过注册名字向数据库查询数据 select username, password, sex, language, city from user where username=?
        // 获取数据库连接对象
        Connection conn = JDBCUtils.getConnection();
        // 编写sql
        String sql = "select username, password, sex, language, city from user where username=?";
        // 创建sql预编译执行对象
        PreparedStatement stat = conn.prepareStatement(sql);

        // 替换占位符
        stat.setString(1, username);

        // 执行sql语句
        ResultSet rest = stat.executeQuery();
        // 将rest结果封装到user对象当中
        User user = null;
        while (rest.next()) {
            // 取出数据
            user = new User();
            user.setUsername(rest.getString("username"));
            user.setId(rest.getInt("id"));
            user.setPassword(rest.getString("password"));
            user.setSex(rest.getString("sex"));
            user.setLanguage(rest.getString("language"));
            user.setCity(rest.getString("city"));
        }
        // 判断是否有结果
        if (user == null) {
            // 可以注册数据
            String insert = "insert into user(username, password, sex, language, city) values(?, ?, ?, ?, ?)";
            stat = conn.prepareStatement(insert);
            // 替换占位符
            stat.setString(1, username);
            stat.setString(2, password);
            stat.setString(3, sex);
            stat.setString(4, Arrays.toString(languages));
            stat.setString(5, city);

            // 执行sql
            stat.executeUpdate();

            // 响应注册成功页面
            response.getWriter().println("<h1>注册成功</h1>");
        }else {
            // 提示用户注册失败，跳转到注册失败页面
            response.getWriter().println("<h1>注册失败</h1>");
        }


    }
}
